package com.younio.local.compnent.datasource;

import com.younio.local.LocalApplication;
import com.younio.local.compnent.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@Order(12)
public class MultiDataSourceStartRunner implements CommandLineRunner {

    @Override
    @SuppressWarnings("unchecked")
    public void run(String... args) {
        log.info("Start to load multi datasource");
        LocalApplication.setLabel("正在连接数据库");
        AbstractRoutingDataSource routingDataSource = SpringContextHolder.getBean(AbstractRoutingDataSource.class);
        Map map = SpringContextHolder.getBeansOfType(DataSource.class);
        Map<Object, Object> datasourceMap = new HashMap<>();
        map.forEach((k, v) -> {
            if (!(v instanceof AbstractRoutingDataSource)) {
                log.info("Loading data source: " + k);
                datasourceMap.put(k, v);
                MultiDataSourceHolder.add((String) k);
            }
        });
        routingDataSource.setTargetDataSources(datasourceMap);
        log.info("Init routing dataSource");

        LocalApplication.setLabel("初始化数据库连接");

        routingDataSource.afterPropertiesSet();
        LocalApplication.setLabel("数据库连接成功");
    }
}
